package com.ccrfid.rmc6.lbservice3.manager;

import com.ccrfid.rmc6.entity.device.CardActiveEntity;
import com.ccrfid.rmc6.entity.device.CardEntity;
import com.ccrfid.rmc6.lbservice3.pojo.alarm.AlarmCall;
import com.ccrfid.rmc6.lbservice3.pojo.alarm.AlarmCutoffStatus;
import com.ccrfid.rmc6.lbservice3.pojo.alarm.AlarmLowpowerStatus;
import com.ccrfid.rmc6.lbservice3.pojo.alarm.AlarmOnlineStatus;
import com.ccrfid.rmc6.lbservice3.pojo.msg.*;
import com.ccrfid.rmc6.pojo.Constants;
import com.ccrfid.rmc6.service.device.CardDownLinkService;
import com.ccrfid.rmc6.service.device.CardService;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class CardStatusManager {
    private static final Logger logger = LoggerFactory.getLogger(CardStatusManager.class);
    @Autowired
    private EventBus eventBus;
    @Autowired
    private CardService cardService;
    @Autowired
    private CardDownLinkService cardDownLinkService;
    @Value("${time.offline}")
    private Integer timeOffline;
    @Value("${card.check.offline.open}")
    private Boolean alarmCheckOfflineOpen;

    @PostConstruct
    private void init() {
        this.eventBus.register(this);
        //设备离线检测线程
        if (!alarmCheckOfflineOpen) {
            //不开启离线检测线程
            logger.debug("** card checkOffline: {}", alarmCheckOfflineOpen);
            return;
        }
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        TimeUnit.MILLISECONDS.sleep(timeOffline / 3);
                        List<CardEntity> list = cardService.getAllCards();
                        long timeNow = new Date().getTime();
                        for (CardEntity cardEntity : list) {
                            CardActiveEntity activeEntity = cardService.getCardActive(cardEntity.getCardNumber());
                            long updateTime = 0;
                            if (activeEntity != null) {
                                updateTime = (cardEntity.getUpdateTime().getTime() > activeEntity.getUpdateTime().getTime()
                                        ? cardEntity.getUpdateTime().getTime()
                                        : activeEntity.getUpdateTime().getTime());
                            } else {
                                updateTime = cardEntity.getUpdateTime().getTime();
                            }
                            if ((timeNow - updateTime) > timeOffline) {
                                //标签已离线
                                if (cardEntity.getOnlineStatus() == null ||
                                        cardEntity.getOnlineStatus().equals(Constants.ONLINE_STATUS.ONLINE.id)) {
                                    //1.更新在线状态为离线
                                    cardEntity.setOnlineStatus(Constants.ONLINE_STATUS.OFFLINE.id);
                                    cardService.updateCard(cardEntity);
                                    //2.离线告警
                                    logger.debug("post AlarmOffline, cardNumber: {}", cardEntity.getCardNumber());
                                    eventBus.post(new AlarmOnlineStatus(
                                            cardEntity.getCardNumber(), Constants.ONLINE_STATUS.OFFLINE.id, timeNow));
                                    //3.水墨卡片停止下发信息
                                    cardDownLinkService.stopDownLinkInfo(cardEntity);
                                }
                            }
                        }
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        });
        thread.start();
        logger.debug("** card checkOffline: {}, start check thread...", alarmCheckOfflineOpen);
    }

    @Subscribe
    public void onMsgLocateActive(MsgLocateActive msgLocateActive) {
        CardEntity cardEntity = cardService.getCardByCardNumber(msgLocateActive.getCardNumber());
        if (cardEntity != null) {
            //1.更新定位信息
            cardService.updateCardActive(msgLocateActive);
            //2.标签上线
            if (msgLocateActive.getCurrentFloorNumber() != null
                    && (cardEntity.getOnlineStatus() == null
                        || cardEntity.getOnlineStatus().equals(Constants.ONLINE_STATUS.OFFLINE.id))) {
                //1.更新在线状态
                cardEntity.setOnlineStatus(Constants.ONLINE_STATUS.ONLINE.id);
                cardService.updateCard(cardEntity);
                //2.标签上线
                logger.debug("post AlarmOnline, cardNumber: {}", cardEntity.getCardNumber());
                eventBus.post(new AlarmOnlineStatus(
                        cardEntity.getCardNumber(), Constants.ONLINE_STATUS.ONLINE.id, msgLocateActive.getTime()));
                //3.水墨卡片校时/下发信息
                cardDownLinkService.downLinkInfo(cardEntity);
                cardDownLinkService.timing(cardEntity.getHexNumber().toLowerCase());
            }
        }
    }

    @Subscribe
    public void onMsgCut(MsgCut msgCut) {
        CardEntity cardEntity = cardService.getCardByCardNumber(msgCut.getCardNumber());
        if (cardEntity != null) {
            //1.更新剪断状态
            cardEntity.setCutoffStatus(msgCut.getCutoffStatus());
            cardService.updateCard(cardEntity);
            //2..剪断状态告警：1-剪断; 0-恢复正常
            logger.debug("post AlarmCutoffStatus, cardNumber: {}, cutoffStatus: {}", msgCut.getCardNumber(), msgCut.getCutoffStatus());
            eventBus.post(new AlarmCutoffStatus(msgCut.getCardNumber(), msgCut.getCutoffStatus(), msgCut.getTime()));
        }
    }

    @Subscribe
    public void onMsgKeepalive(MsgKeepalive msgKeepalive) {
        CardEntity cardEntity = cardService.getCardByCardNumber(msgKeepalive.getCardNumber());
        if (cardEntity != null) {
            if (cardEntity.getOnlineStatus() == null ||
                    cardEntity.getOnlineStatus().equals(Constants.ONLINE_STATUS.OFFLINE.id)) {
                //2.标签上线
                logger.debug("post AlarmOnline, cardNumber: {}", cardEntity.getCardNumber());
                eventBus.post(new AlarmOnlineStatus(
                        cardEntity.getCardNumber(), Constants.ONLINE_STATUS.ONLINE.id, msgKeepalive.getTime()));
            }
            cardEntity.setOnlineStatus(Constants.ONLINE_STATUS.ONLINE.id);
            cardService.updateCard(cardEntity);
        }
    }

    @Subscribe
    public void onMsgCall(MsgCall msgCall) {
        //1.呼叫告警
        logger.debug("post AlarmCall, cardNumber: {}", msgCall.getCardNumber());
        eventBus.post(new AlarmCall(msgCall.getCardNumber(), msgCall.getTime()));
    }

    @Subscribe
    public void onMsgPowerCheck(MsgPowerCheck msgPowerCheck) {
        CardEntity cardEntity = cardService.getCardByCardNumber(msgPowerCheck.getCardNumber());
        if (cardEntity != null) {
            //1.更新电量值
            cardEntity.setBattery(msgPowerCheck.getBattery());
            cardService.updateCard(cardEntity);
        }
    }

    @Subscribe
    public void onMsgHeartRate(MsgHeartRate msgHeartRate) {
        CardEntity cardEntity = cardService.getCardByCardNumber(msgHeartRate.getCardNumber());
        if (cardEntity != null) {
            //1.更新心率值
            cardEntity.setHeartRate(msgHeartRate.getHeartRate());
            cardService.updateCard(cardEntity);
        }
    }

    @Subscribe
    public void onMsgNoPower(MsgNoPower msgNoPower) {
        CardEntity cardEntity = cardService.getCardByCardNumber(msgNoPower.getCardNumber());
        if (cardEntity != null) {
            //1.更新低电状态
            cardEntity.setLowpowerStatus(1);
            cardService.updateCard(cardEntity);
            //2.低电告警
            logger.debug("post AlarmLowpower, cardNumber: {}", msgNoPower.getCardNumber());
            eventBus.post(new AlarmLowpowerStatus(msgNoPower.getCardNumber(),
                    Constants.LOWPOWER_STATUS.LOWPOWER.id, msgNoPower.getTime()));
        }
    }

    @Subscribe
    public void onMsgReset(MsgReset msgReset) {
        CardEntity cardEntity = cardService.getCardByCardNumber(msgReset.getCardNumber());
        if (cardEntity != null) {
            //1.更新电量值
            cardEntity.setBattery(msgReset.getBattery());
            cardService.updateCard(cardEntity);
        }
    }

    @Subscribe
    public void onMsgLowPowerStatus(MsgLowpowerStatus msgLowpowerStatus) {
        CardEntity cardEntity = cardService.getCardByCardNumber(msgLowpowerStatus.getCardNumber());
        if (cardEntity != null) {
            if (!msgLowpowerStatus.getLowpowerStatus().equals(cardEntity.getLowpowerStatus())) {
                //1.更新低电状态
                cardEntity.setLowpowerStatus(msgLowpowerStatus.getLowpowerStatus());
                cardService.updateCard(cardEntity);
                //2.低电状态告警：低电/恢复
                logger.debug("post AlarmLowpowerStatus, cardNumber: {}, lowpowerStatus: {}",
                        msgLowpowerStatus.getCardNumber(), msgLowpowerStatus.getLowpowerStatus());
                eventBus.post(new AlarmLowpowerStatus(msgLowpowerStatus.getCardNumber(),
                        msgLowpowerStatus.getLowpowerStatus(), msgLowpowerStatus.getTime()));
            }
        }
    }

}
